package com.qs.oauth2.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier(value = "myUserServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * HttpSecurity中配置所有请求的安全验证
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors() //关闭CSRF攻击防护，开启跨域
                .and()
                .authorizeRequests()
                .antMatchers("/login", "/oauth/check_token").permitAll()
                .antMatchers("/user/userDetail").access("#oauth2.hasScope('user_scope')")
                .anyRequest().authenticated()
                .and()
                .formLogin() //启用表单登录（会向过滤器链中加入UsernamePasswordAuthenticationFilter）
                .and()
                .logout().clearAuthentication(true).invalidateHttpSession(true); //登出
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/static/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //注意这里注册到ioc容器中的AuthenticationManager实例名不要写成authenticationManager，
    // 会不断执行org.springframework.security.authentication.ProviderManager.authenticate方法，造成栈溢出错误
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
